package start;

import java.net.InetSocketAddress;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionInitializer;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import connect.MessageCode;
import connect.MyIoHandler;

/**
 * @author Administrator
 * 
 */
public class ClientStart
{

	public static IoSession sess;
	
	public static long time;

	public static void main(String[] args)
	{

		startConnector();
		
//		while(true)
		{
			if(time < System.currentTimeMillis())
			{
				time = System.currentTimeMillis()+1;
				
				if(sess != null)
					sendMessage();
				
			}
			
			
		}
		
	}

	private static void sendMessage()
    {
		try
		{
//			ByteBuffer data = new ByteBuffer();
//			data.writeInt(MessageCode.TEST.BID);
//			data.writeInt(MessageCode.TEST.TEST);
//			data.writeInt(1234);
			
			 IoBuffer b = IoBuffer.allocate(16);
			 b.putInt(12);
			 b.putInt(MessageCode.TEST.BID);
			 b.putInt(MessageCode.TEST.TEST);
			 b.putInt(1234);
			 b.flip();
			
	        sess.write(b);
		        
		}catch (Exception e) {
			e.printStackTrace();
		}
       
    }

	private static void startConnector()
	{
		NioSocketConnector connector = new NioSocketConnector();
		connector.setHandler(new MyIoHandler());
		// connector.getFilterChain().addLast("codec", new
		// ProtocolCodecFilter());
		connector.getSessionConfig().setWriterIdleTime(1000 * 20);
		connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 240);
		connector.getSessionConfig().setTcpNoDelay(true);

		connector.connect(new InetSocketAddress("0.0.0.0", 9003),
		        new IoSessionInitializer<ConnectFuture>()
		        {
					
			        @Override
			        public void initializeSession(IoSession session,
			                ConnectFuture arg1)
			        {
				        try {
					        sess = session;
					        sendMessage();
				        } catch (Exception e) {
					        e.printStackTrace();
				        }

			        }
		        });
		
		connector.setHandler(new ClientIoHandler());
		
		
	}

	
}
